﻿using System.Net;
using Microsoft.AspNetCore.Mvc.Filters;
using NewLife;
using PMS.WebApi.Models;

namespace PMS.WebApi.Utils
{
    public class ApiAuthAttribute : ActionFilterAttribute
    {
        readonly string[] _role;
        /// <summary>
        /// 用户权限校验
        /// </summary>
        /// <param name="role">可以通过的权限</param>
        public ApiAuthAttribute(params string[] role)
        {
            _role = role;
        }

        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            //url获取token
            var request = actionContext.HttpContext.Request;
            //var content = request.Properties["MS_HttpContext"] as HttpContext;
            //var ip = actionContext.HttpContext.Connection.RemoteIpAddress.ToString();
            var ip = actionContext.HttpContext.Request.Headers["X-Real-IP"].ToString();
            var token = actionContext.HttpContext.Request.Headers["Access-Token"].ToString();

            try
            {
                if (ip.IsNullOrEmpty())
                    ip = actionContext.HttpContext.Connection.RemoteIpAddress.ToString();

                #region Access-Token 校验
                var token_des = EncryptHelper.Base64Decode(token);
                var token_result = EncryptHelper.DESDecrypt(token_des);
                if (token_result != ip)
                    throw new Exception("Invalid access token!");
                #endregion

                base.OnActionExecuting(actionContext);
            }
            catch (Exception ex)
            {
                var response = actionContext.HttpContext.Response;
                response.StatusCode = (int)HttpStatusCode.Forbidden;
                var content = new ResultMsg
                {
                    success = false,
                    message = "服务端拒绝访问：您没有权限或者网络异常！Access denied by the server: You do not have permission or there is a network abnormality!"
                };
                response.WriteAsJsonAsync(content);
                //response.WriteAsync(content.ToJson(), Encoding.UTF8);
            }
        }
    }
}
